﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Services.AI.WebApi.Model;
using Services.AI.WebApi.Request;
using Services.AI.WebApi.Response;
using Services.Initial.PublicProject.PublicClass.OutPutModels;
using Services.Initial.PublicProject.PublicMethods;
using Services.InitialProject.Model;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Services.AI.WebApi.Controllers;

[ApiController]
[Route("[controller]/[action]")]
//[Authorize]
public class AIController(IHttpClientFactory httpClientFactory,IOptionsSnapshot<ZhiPuQingYan> zhipuqingyan)
{
    private readonly string apiKey = zhipuqingyan.Value.ApiKey;
    private readonly IHttpClientFactory httpClientFactory = httpClientFactory;

    [HttpPost]
    public async Task<OutputModel<GetAiResultResponse>> GetAiResult([FromBody] GetAiResultRequest req)
    {
        var requestData = new RequestData
        {
            Prompt = new[]
            {
                new Prompt
                {
                    Role = "user",
                    Content = req.Input
                }
            }
        };

        var client = httpClientFactory.CreateClient();
        var token = Token.GenerateToken(apiKey, 10000000);
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
        var requestUri = "https://open.bigmodel.cn/api/llm-application/open/model-api/1779406041692471297/invoke";
        var optionsS = new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        };
        var Content = JsonSerializer.Serialize(requestData, optionsS);
        var httpcontent = new StringContent(Content, Encoding.UTF8, "application/json");
        var responseMessage = await client.PostAsync(requestUri, httpcontent);
        if (responseMessage.IsSuccessStatusCode)
        {
            try
            {
                var result = await responseMessage.Content.ReadAsStringAsync();
                JsonSerializerOptions optionsD = new() { PropertyNameCaseInsensitive = true,NumberHandling = JsonNumberHandling.AllowReadingFromString };
                var jsonParse = JsonSerializer.Deserialize<ResponseData>(result, optionsD);
                // 处理嵌套 JSON 字符串
               // string innerJson = JsonSerializer.Deserialize<string>(jsonParse.Data.Content);
                var contentData = JsonSerializer.Deserialize<ActitivityContent>(jsonParse.Data.Content);
                return OutPutMethod<GetAiResultResponse>.Success(new GetAiResultResponse
                {
                    IsActivity = contentData.IsActivity,
                    Content = contentData.Content,
                    ActivityIds = contentData.ActivityIds,
                });
            }
            catch
            {
                return OutPutMethod<GetAiResultResponse>.Failure("提问有误，请重新输入。");
            }

        }
        else
        {
            return OutPutMethod<GetAiResultResponse>.Failure("回答失败，请稍后再试。");
        }

    }

}
